package com.socket.nio.nio.sticky.delimiterbased;

import com.socket.nio.nio.constant.NioConstant;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * Delimiter 服务端业务处理器
 *
 * @author Hexudong
 * @date 2025/5/5
 */
public class DelimiterServerHandler extends SimpleChannelInboundHandler<String> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, String msg) {
    // 收到的消息已经自动去除了分隔符
    System.out.println("Server received: " + msg);

    // 响应客户端，添加分隔符
    String response = "Echo: " + msg + NioConstant.DELIMITER;
    ctx.writeAndFlush(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    System.out.println("异常" + cause.getMessage());
    ctx.close();
  }
}
